package com.nbcio.modules.erp.goods.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nbcio.modules.erp.goods.service.IErpGoodsPageService;
import com.nbcio.modules.erp.stock.entity.ErpGoodsStock;
import com.nbcio.modules.erp.stock.service.IErpGoodsStockService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import com.nbcio.modules.erp.goods.entity.ErpGoodsPrice;
import com.nbcio.modules.erp.goods.entity.ErpGoods;
import com.nbcio.modules.erp.goods.vo.ErpGoodsPage;
import com.nbcio.modules.erp.goods.service.IErpGoodsService;
import com.nbcio.modules.erp.goods.service.IErpGoodsPriceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 商品基础信息
 * @Author: nbacheng
 * @Date:   2023-03-08
 * @Version: V1.0
 */
@Api(tags="商品基础信息")
@RestController
@RequestMapping("/goods/erpGoods")
@Slf4j
public class ErpGoodsController {
	@Autowired
	private IErpGoodsService erpGoodsService;
	@Autowired
	private IErpGoodsPriceService erpGoodsPriceService;

	@Autowired
	private IErpGoodsStockService erpGoodsStockService;
	
	/**
	 * 分页列表查询
	 *
	 * @param erpGoods
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "商品基础信息-分页列表查询")
	@ApiOperation(value="商品基础信息-分页列表查询", notes="商品基础信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ErpGoods erpGoods,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ErpGoods> queryWrapper = QueryGenerator.initQueryWrapper(erpGoods, req.getParameterMap());
		Page<ErpGoods> page = new Page<ErpGoods>(pageNo, pageSize);
		IPage<ErpGoods> pageList = erpGoodsService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param erpGoodsPage
	 * @return
	 */
	@AutoLog(value = "商品基础信息-添加")
	@ApiOperation(value="商品基础信息-添加", notes="商品基础信息-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ErpGoodsPage erpGoodsPage) {
		ErpGoods erpGoods = new ErpGoods();
		BeanUtils.copyProperties(erpGoodsPage, erpGoods);
		erpGoodsService.saveMain(erpGoods, erpGoodsPage.getErpGoodsPriceList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param erpGoodsPage
	 * @return
	 */
	@AutoLog(value = "商品基础信息-编辑")
	@ApiOperation(value="商品基础信息-编辑", notes="商品基础信息-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ErpGoodsPage erpGoodsPage) {
		ErpGoods erpGoods = new ErpGoods();
		BeanUtils.copyProperties(erpGoodsPage, erpGoods);
		ErpGoods erpGoodsEntity = erpGoodsService.getById(erpGoods.getId());
		if(erpGoodsEntity==null) {
			return Result.error("未找到对应数据");
		}
		erpGoodsService.updateMain(erpGoods, erpGoodsPage.getErpGoodsPriceList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商品基础信息-通过id删除")
	@ApiOperation(value="商品基础信息-通过id删除", notes="商品基础信息-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		erpGoodsService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "商品基础信息-批量删除")
	@ApiOperation(value="商品基础信息-批量删除", notes="商品基础信息-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.erpGoodsService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商品基础信息-通过id查询")
	@ApiOperation(value="商品基础信息-通过id查询", notes="商品基础信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ErpGoods erpGoods = erpGoodsService.getById(id);
		if(erpGoods==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(erpGoods);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商品价格信息通过主表ID查询")
	@ApiOperation(value="商品价格信息主表ID查询", notes="商品价格信息-通主表ID查询")
	@GetMapping(value = "/queryErpGoodsPriceByMainId")
	public Result<?> queryErpGoodsPriceListByMainId(@RequestParam(name="id",required=true) String id) {
		List<ErpGoodsPrice> erpGoodsPriceList = erpGoodsPriceService.selectByMainId(id);
		return Result.OK(erpGoodsPriceList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param erpGoods
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ErpGoods erpGoods) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<ErpGoods> queryWrapper = QueryGenerator.initQueryWrapper(erpGoods, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<ErpGoods> queryList = erpGoodsService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<ErpGoods> erpGoodsList = new ArrayList<ErpGoods>();
      if(oConvertUtils.isEmpty(selections)) {
          erpGoodsList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          erpGoodsList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<ErpGoodsPage> pageList = new ArrayList<ErpGoodsPage>();
      for (ErpGoods main : erpGoodsList) {
          ErpGoodsPage vo = new ErpGoodsPage();
          BeanUtils.copyProperties(main, vo);
          List<ErpGoodsPrice> erpGoodsPriceList = erpGoodsPriceService.selectByMainId(main.getId());
          vo.setErpGoodsPriceList(erpGoodsPriceList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "商品基础信息列表");
      mv.addObject(NormalExcelConstants.CLASS, ErpGoodsPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商品基础信息数据", "导出人:"+sysUser.getRealname(), "商品基础信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ErpGoodsPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ErpGoodsPage.class, params);
              for (ErpGoodsPage page : list) {
                  ErpGoods po = new ErpGoods();
                  BeanUtils.copyProperties(page, po);
                  erpGoodsService.saveMain(po, page.getErpGoodsPriceList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }


	 @AutoLog(value = "商品上架")
	 @ApiOperation(value="商品上架", notes="商品上架")
	 @DeleteMapping(value = "/listing")
	 public Result<?> listing(@RequestParam(name="id",required=true) String id) {
		 ErpGoods erpGoodsEntity = erpGoodsService.getById(id);
		 if(erpGoodsEntity==null) {
			 return Result.error("未找到对应数据");
		 }else if("1".equals(String.valueOf(erpGoodsEntity.getListingStatus()))){
			 return Result.error("商品已上架");
		 }
		 erpGoodsService.listing(id);
		 return Result.OK("上架成功!");
	 }

	 @AutoLog(value = "商品下架")
	 @ApiOperation(value="商品下架", notes="商品下架")
	 @DeleteMapping(value = "/deListing")
	 public Result<?> deListing(@RequestParam(name="id",required=true) String id) {
		 ErpGoods erpGoodsEntity = erpGoodsService.getById(id);
		 if(erpGoodsEntity==null) {
			 return Result.error("未找到对应数据");
		 }else if(!"1".equals(String.valueOf(erpGoodsEntity.getListingStatus()))){
			 return Result.error("商品未上架");
		 }
		 erpGoodsService.deListing(id);
		 return Result.OK("下架成功!");
	 }

	 /**
	  * 商品批量上架
	  * @param ids 商品的id用逗号隔开
	  * @return
	  */
	 @AutoLog(value = "商品批量上架")
	 @ApiOperation(value="商品批量上架", notes="商品批量上架")
	 @DeleteMapping(value = "/batchListing")
	 public Result<?> batchListing(@RequestParam(name="ids",required=true) String ids) {
		 String[] idArr = ids.split(",");
		 for(String id : idArr) {
			 ErpGoods erpGoodsEntity = erpGoodsService.getById(id);
			 if(erpGoodsEntity==null) {
				 return Result.error(erpGoodsEntity.getName()+"未找到对应数据");
			 } else if("1".equals(String.valueOf(erpGoodsEntity.getListingStatus()))){
				 return Result.error(erpGoodsEntity.getName()+"已上架");
			 }
			 erpGoodsService.listing(id);
		 }
		 return Result.OK("批量上架成功!");
	 }


	 /**
	  * 商品批量下架
	  * @param ids 商品的id用逗号隔开
	  * @return
	  */
	 @AutoLog(value = "商品批量下架")
	 @ApiOperation(value="商品批量下架", notes="商品批量下架")
	 @DeleteMapping(value = "/batchDeListing")
	 public Result<?> batchDeListing(@RequestParam(name="ids",required=true) String ids) {
		 String[] idArr = ids.split(",");
		 for(String id : idArr) {
			 ErpGoods erpGoodsEntity = erpGoodsService.getById(id);
			 if(erpGoodsEntity==null) {
				 return Result.error(erpGoodsEntity.getName()+"未找到对应数据");
			 } else if("2".equals(String.valueOf(erpGoodsEntity.getListingStatus()))){
				 return Result.error(erpGoodsEntity.getName()+"已下架");
			 }
			 erpGoodsService.deListing(id);
		 }

		 return Result.OK("批量下架成功");
	 }


	 /**
	  * 根据商品id查询商品详情
	  * @param id 商品的id
	  * @return
	  */
	 @AutoLog(value = "根据商品id查询商品详情")
	 @ApiOperation(value="根据商品id查询商品详情", notes="根据商品id查询商品详情")
	 @GetMapping(value = "/detail")
//	 @GetMapping(value = "/detailAsync")
	 public Result<?> detail(@RequestParam(name="id",required=true) String id) {
		 Map<String, Object> map = erpGoodsService.detail(id);
		 return Result.OK("查询成功",map);
	 }

	 @AutoLog(value = "根据商品id查询商品详情(异步)")
	 @ApiOperation(value="根据商品id查询商品详情(异步)", notes="根据商品id查询商品详情(异步)")
//	 @GetMapping(value = "/detail")
	 public Result<?> detailAsync(@RequestParam(name="id",required=true) String id) throws ExecutionException, InterruptedException {
		 CompletableFuture<Map<String, Object>> mapCompletableFuture = erpGoodsService.fetchOptimizedDataAsync(id);
		 Map<String, Object> map = mapCompletableFuture.get();
		 return Result.OK("查询成功",map);
	 }

	 /**
	  * 根据商品分类id查询商品详情
	  * @param categoryId 商品分类id
	  * @return
	  */
	 @AutoLog(value = "根据商品分类id查询商品详情")
	 @ApiOperation(value="根据商品分类id查询商品详情", notes="根据商品分类id查询商品详情")
//	 @GetMapping(value = "/detailByCategoryIdAsync")
	 @GetMapping(value = "/detailByCategoryId")
	 public Result<?> detailByCategoryId(@RequestParam(name="categoryId",required=true) String categoryId,@RequestParam("page") int page,@RequestParam("size") int size) {
		 List<Map<String, Object>> result = erpGoodsService.detailByCategoryId(categoryId,page,size);
		 return Result.OK("查询成功",result);
	 }

	 @AutoLog(value = "根据商品分类id查询商品详情(异步)")
	 @ApiOperation(value="根据商品分类id查询商品详情(异步)", notes="根据商品分类id查询商品详情(异步)")
//	 @GetMapping(value = "/detailByCategoryId")
	 public Result<?> detailByCategoryIdAsync(@RequestParam(name="categoryId",required=true) String categoryId,@RequestParam("page") int page,@RequestParam("size") int size) throws ExecutionException, InterruptedException {
		 CompletableFuture<List<Map<String, Object>>> listCompletableFuture = erpGoodsService.fetchErpGoodsDataAsync(categoryId, page, size);
		 List<Map<String, Object>> result = listCompletableFuture.get();
		 return Result.OK("查询成功",result);
	 }


	 /**
	  * 根据名称模糊查询商品详情
	  * @param name
	  * @return
	  */
	 @AutoLog(value = "根据名称模糊查询商品详情")
	 @ApiOperation(value="根据名称模糊查询商品详情", notes="根据名称模糊查询商品详情")
	 @GetMapping(value = "/queryGoodsByName")
//	 @GetMapping(value = "/queryGoodsByNameAsync")
	 public Result<?> queryGoodsByName(@RequestParam(name="name") String name) {
		 List<Map<String, Object>> listMap = erpGoodsService.queryGoodsByName(name);
		 return Result.OK("查询成功",listMap);
	 }

	 @AutoLog(value = "根据名称模糊查询商品详情(异步)")
	 @ApiOperation(value="根据名称模糊查询商品详情(异步)", notes="根据名称模糊查询商品详情(异步)")
//	 @GetMapping(value = "/queryGoodsByName")
	 public Result<?> queryGoodsByNameAsync(@RequestParam(name="name") String name) {
		 List<Map<String, Object>> listMap = erpGoodsService.fetchErpGoodsDataAsync(name);
		 return Result.OK("查询成功",listMap);
	 }

}
